package aygx.ip.spring.boot.starter.service;

import aygx.ip.spring.boot.starter.config.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 暗影孤星
 * @date 2022/7/31 23:05
 * @description
 */
public class IpService {
    private Map<String, Integer> ipCountMap = new HashMap<String, Integer>();

    @Autowired
    private IpProperties ipProperties;
    @Autowired
    private HttpServletRequest httpServletRequest;

    public void count() {
        // 每次调用当前操作，就记录当前访问的IP，然后累加访问次数
        ipCountMap.merge( httpServletRequest.getRemoteAddr(), 1, Integer::sum);
    }


    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?")
    public void print() {

        if (ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())) {
            System.out.println("         IP访问监控");
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.printf("|%18s  |%5d  |%n", key, value);
            }
            System.out.println("+--------------------+-------+");
        } else if (ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())) {
            System.out.println("     IP访问监控");
            System.out.println("+-----ip-address-----+");
            for (String key : ipCountMap.keySet()) {
                System.out.printf("|%18s  |%n", key);
            }
            System.out.println("+--------------------+");
        }

        if (ipProperties.getCycleReset()) {
            ipCountMap.clear();
        }
    }
}
